﻿import "babel-polyfill"
import Vue from 'vue'
import Router from 'vue-router'
import routes from "./router.js"
import App from './app'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './store'
import { getUserInfo, logout } from '@/utils/auth'

import * as filters from '@/filters/'

import ServerMixin from './mixin/ServerMixin'

import '../theme/iconfont/iconfont.css'
import '../theme/common.scss'

import utils from '@/utils'
import vSelect from 'vue-select'

Vue.use(ElementUI);
Vue.use(ServerMixin);
Vue.use(Router);
Vue.component('v-select', vSelect)

Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key]);
})

const router = new Router({ routes });


// 拦截白名单
const whiteList = ['/login', '/clear'];

router.beforeEach((to, from, next) => {

    // 
    if (whiteList.indexOf(to.path) != -1) {

        next()
    } else {

        const userInfo = getUserInfo()
        if (userInfo) {
            next();
        } else {
            const token = utils.getQueryString('token');
            if (utils.isNotEmpty(token)) {
                store.dispatch("login", {
                    token: token,
                    callback(res) {
                        next();
                    }
                });

            } else {
                store.dispatch("logout");
            }
        }
    }
});
new Vue({
    el: '#app',
    template: '<App/>',
    router,
    store,
    components: { App },
    mounted() {
        ServerMixin.Event.$on('login', () => {
            store.dispatch("logout");
        })
    }
});